<template>
  <div class="histogram">
    <h1>柱状图</h1>
    <div ref="chartRef" style="width: 660px; height: 350px"></div>
  </div>
</template>

<script lang="ts" setup>
import { echarts } from '@/utils/echarts'
import type { ECOption } from '@/utils/echarts'
// prettier-ignore
const dataAxis = ['点', '击', '柱', '子', '或', '者', '两', '指', '在', '触', '屏', '上', '滑', '动', '能', '够', '自', '动', '缩', '放'];
// prettier-ignore
const data = [220, 182, 191, 234, 290, 330, 310, 123, 442, 321, 90, 149, 210, 122, 133, 334, 198, 123, 125, 220];
const yMax = 500
const dataShadow = []

for (let i = 0; i < data.length; i++) {
  dataShadow.push(yMax)
}

const chartRef = ref<HTMLDivElement | null>(null)
let myChart: echarts.ECharts | null = null

const option: ECOption = {
  title: {
    text: '特性示例：渐变色 阴影 点击缩放',
    subtext: 'Feature Sample: Gradient Color, Shadow, Click Zoom',
  },
  xAxis: {
    data: dataAxis,
    axisLabel: {
      inside: true,
      color: '#fff',
    },
    axisTick: {
      show: false,
    },
    axisLine: {
      show: false,
    },
    z: 10,
  },
  yAxis: {
    axisLine: {
      show: false,
    },
    axisTick: {
      show: false,
    },
    axisLabel: {
      color: '#999',
    },
  },
  dataZoom: [
    {
      type: 'inside',
    },
  ],
  series: [
    {
      type: 'bar',
      showBackground: true,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#83bff6' },
          { offset: 0.5, color: '#188df0' },
          { offset: 1, color: '#188df0' },
        ]),
      },
      emphasis: {
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#2378f7' },
            { offset: 0.7, color: '#2378f7' },
            { offset: 1, color: '#83bff6' },
          ]),
        },
      },
      data: data,
    },
  ],
}

// Enable data zoom when user click bar.
const zoomSize = 6

onMounted(() => {
  if (chartRef.value) {
    myChart = echarts.init(chartRef.value)
    myChart.setOption(option)
    myChart.on('click', function (params) {
      console.log(dataAxis[Math.max(params.dataIndex - zoomSize / 2, 0)])
      if (myChart) {
        myChart.dispatchAction({
          type: 'dataZoom',
          startValue: dataAxis[Math.max(params.dataIndex - zoomSize / 2, 0)],
          endValue: dataAxis[Math.min(params.dataIndex + zoomSize / 2, data.length - 1)],
        })
      }
    })
  }
})

// 在组件卸载前执行的操作
onBeforeUnmount(() => {
  // 如果echarts实例存在，则销毁实例
  if (myChart) {
    myChart.dispose()
    myChart = null // 清空 myChart 变量
  }
  chartRef.value = null // 清空 chartRef 变量 myChart.dispose()
})
</script>

<style scoped lang="scss"></style>
